/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.service;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.service.ServiceException;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.ShopAddDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @author ThinkGem
 * @version 2013-12-05
 */
@Service
@Transactional(readOnly = false)
public class ShopAddService extends BaseService {
	
	@Autowired
	private ShopAddDao shopAddDao;
	@Autowired
	private UserDao userDao;
	
	public Page<User> findUser(Page<User> page, User user) {
		// 设置分页参数
		user.setPage(page);
		// 执行分页查询
 		List list=shopAddDao.findList(user);
		page.setList(list);
		return page;
	}

	//添加或修改
	@Transactional(readOnly = false)
	public void saveUser(User user) {
		User users=shopAddDao.userAreas(UserUtils.getUser().getId());
		user.setProvinces(users.getProvinces());
		user.setCitys(users.getCitys());
		user.setAreas(users.getAreas());
		user.setAgentId(UserUtils.getUser().getId());
		Role role=new Role();
		role.setId("8");
		user.setRole(role);
		if (StringUtils.isBlank(user.getId())){
			user.preInsert();
			user.setCreateTime(new Date());
			shopAddDao.insert(user);
			shopAddDao.inserUserRole(user);
			//门店添加成功后，初始化麻雀钱包账户
			TbMpWallet tbMpWallet=new TbMpWallet();
			tbMpWallet.setUid(user.getId());
			tbMpWallet.setCreateTime(new Date());
			tbMpWallet.setUpdateTime(new Date());
			tbMpWallet.setUserType(2);
			Integer rows=shopAddDao.insertMpWallet(tbMpWallet);
		}else{
			// 清除原用户机构用户缓存
			User oldUser = userDao.get(user.getId());
			// 更新用户数据
			user.preUpdate();
			user.setUpdateDate(new Date());
			shopAddDao.update(user);
		}
		// 更新用户与角色关联
		//userDao.deleteUserRole(user);
		// 清除用户缓存
		UserUtils.clearCache(user);
	}
	//得到商户所在的省，市，区
	public User userAreas(String uid){
		return shopAddDao.userAreas(uid);
	}
	//根据id得到店铺信息
	public TbShop viewShop(Integer id){
		return shopAddDao.viewShop(id);
	}
}

